package com.tianji.promotion.handler;

import com.tianji.common.utils.ObjectUtils;
import com.tianji.promotion.domain.dto.UserCouponDTO;
import com.tianji.promotion.service.IUserCouponService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import static com.tianji.common.constants.MqConstants.Exchange.PROMOTION_EXCHANGE;
import static com.tianji.common.constants.MqConstants.Key.COUPON_RECEIVE;

/**
 * @author Xinxuan Zhuo
 * @version 2024/3/22
 * <p>
 *
 * </p>
 */

@Slf4j
@RequiredArgsConstructor
@Component
public class PromotionMqHandler {

    private final IUserCouponService userCouponService;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "coupon.receive.queue", durable = "true"),
            exchange = @Exchange(name = PROMOTION_EXCHANGE, type = ExchangeTypes.TOPIC),
            key = COUPON_RECEIVE
    ))
    public void listenCouponReceiveMessage(UserCouponDTO uc) {
        if (log.isInfoEnabled()) {
            log.info("接收到用户：{}，领取优惠券：{}消息，序列号是：{}",
                    uc.getUserId(),
                    uc.getCouponId(),
                    ObjectUtils.isNotEmpty(uc.getSerialNum()) ? uc.getSerialNum() : null);
        }
        userCouponService.checkAndCreateUserCoupon(uc);
    }
}
